<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								库存表
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<div class="static-content-item">
							<div>商品信息</div>
						</div>
						<el-form-item label="商品编码" prop="productCode">
							<el-input v-model="formData.productCode" placeholder="自动生成无需填写" type="text" readonly
								clearable></el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="商品名称" prop="productName">
									<el-input placeholder="请填写" v-model="formData.productName" type="text"
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="规格型号" prop="model">
									<el-input placeholder="请填写" v-model="formData.model" type="text"
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="商品分类" prop="productClassificationId">
									<el-input class="my" readonly type="text" v-model="formData.productClassificationId"
										clearable>
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${productClassificationIndex===key?'#fff':''};${productClassificationIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in productClassificationTags" :key="key"
													:checked="productClassificationIndex===key"
													@change="tagChange(key,'productClassificationId')">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="单位" prop="unitId">
									<el-input class="my" readonly type="text" v-model="formData.unitId" clearable>
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${unitIndex===key?'#fff':''};${unitIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in unitTags" :key="key" :checked="unitIndex===key"
													@change="tagChange(key,'unitId')">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="产品图片" prop="imageUrl">
									<el-input class="my" readonly type="text" clearable>
										<template #prefix>
											<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
												:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
												:limit="1">
												<el-button v-if="!formData.imageUrl" text :icon="UploadFilled">
													上传图片
												</el-button>
												<el-image v-else preview-teleported style="width: 30px; height: 30px;margin: 10px auto;" :src="formData.imageUrl" :preview-src-list="[formData.imageUrl]" />
											</el-upload>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="仓库" prop="warehouse">
									<el-select @clear="selectClear('warehouse')" v-model="formData.warehouse"
										@change="(value:any)=>selectChange(value,'warehouse')" multiple ref="warehouse"
										clearable>
										<el-option v-for="item in warehouseOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="warehouseOption[warehouseIndex]?.color">
															<component :is="warehouseOption[warehouseIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{warehouseOption[warehouseIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>商品价格</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="成本单价" prop="costPrice">
									<el-input placeholder="请填写" type="number" v-model="formData.costPrice" clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="销售单价" prop="sellingPrice">
									<el-input placeholder="请填写" type="number" v-model="formData.sellingPrice" clearable>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>库存信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item class="form-item-bg" label="当前库存数量" prop="currentInventory">
									<el-input placeholder="请填写" type="number" v-model="formData.currentInventory"
										clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item class="form-item-bg" label="采购在途数量" prop="onWayAmount">
									<el-input placeholder="请填写" type="number" v-model="formData.onWayAmount" clearable>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="期初库存数量" prop="initialInventory">
									<el-input placeholder="请填写" type="number" v-model="formData.initialInventory"
										clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="库存下限" prop="stockLowerLimit">
									<el-input placeholder="请填写" type="number" v-model="formData.stockLowerLimit"
										clearable>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<levitation v-if="element" ref="levitationRef" :types="types" :params="levitationParams"
				:observerElement="scrollbarRef" :options="options" :element="element" @change="levitationChange" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, UploadFilled, Briefcase } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	import { ElMessage, FormInstance } from 'element-plus';
	import { url } from '../../../utils/config';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	const activeName = ref('order');
	// 表单
	const formData = ref({
		productCode: null,//商品编码
		productName: null,//商品名称
		model: null,//规格型号
		productClassificationId: null,//商品分类 tag
		unitId: null,//单位
		imageUrl: null,//产品图片
		files: [],//文件
		currentInventory: null,//当前库存数量
		onWayAmount: null,//采购在途数量
		initialInventory: null,//期初库存数量
		stockLowerLimit: null,//库存下限
		warehouseId: null,//仓库
		warehouse: [],
		costPrice: null,//成本单价
		sellingPrice: null,//销售单价
	});
	//验证
	const rules = reactive({
		productCode: [],//商品编码
		productName: [{ required: true, message: '不能为空', trigger: 'blur' }],//商品名称
		model: [{ required: true, message: '不能为空', trigger: 'blur' }],//规格型号
		productClassificationId: [{ required: true, message: '不能为空', trigger: 'blur' }],//商品分类 tag
		unitId: [{ required: true, message: '不能为空', trigger: 'blur' }],//单位
		imageUrl: [],//产品图片
		currentInventory: [{ required: true, message: '不能为空', trigger: 'blur' }],//当前库存数量
		onWayAmount: [{ required: true, message: '不能为空', trigger: 'blur' }],//采购在途数量
		initialInventory: [{ required: true, message: '不能为空', trigger: 'blur' }],//期初库存数量
		stockLowerLimit: [{ required: true, message: '不能为空', trigger: 'blur' }],//库存下限
		warehouse: [{ required: true, message: '不能为空', trigger: 'blur' }],//仓库
		costPrice: [{ required: true, message: '不能为空', trigger: 'blur' }],//成本单价
		sellingPrice: [{ required: true, message: '不能为空', trigger: 'blur' }],//销售单价
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//商品分类
	const productClassificationTags = ref([]);
	const productClassificationIndex = ref(-1);
	//单位
	const unitTags = ref([]);
	const unitIndex = ref(-1);
	//仓库
	const warehouseOption = ref([]);
	const warehouseIndex = ref(-1);
	const warehouse = ref(null);

	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getproductClassificationList();
				getunitList();
				getwarehouseList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		const result = await request({
			url: '/demand/selectPurchaseProductById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'warehouse', //哪一个下拉框，根据ref
			option: warehouseOption, //下拉列表选项
			indexVar: warehouseIndex, //当前选中项
			idVar: 'warehouseId', //当前id值
			blurRef: warehouse, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		if (type === 'productClassificationId') {
			if (productClassificationIndex.value === index) {
				formData.value[type] = 0;
				productClassificationIndex.value = -1;
				return;
			}
			productClassificationIndex.value = index;
			formData.value[type] = productClassificationTags.value[index].value;
		}
		if (type === 'unitId') {
			if (unitIndex.value === index) {
				formData.value[type] = 0;
				unitIndex.value = -1;
				return;
			}
			unitIndex.value = index;
			formData.value[type] = unitTags.value[index].value;
		}
	}
	//获取商品分类
	const getproductClassificationList = async () => {
		const data = await getShipments('product_classification', 'tag');
		console.log('getproductClassificationList --->', data);
		productClassificationTags.value = [];
		data.forEach((item : any, key : number) => {
			productClassificationTags.value.push(item);
			if (formData.value.productClassificationId === item.value) {
				productClassificationIndex.value = key;
			}
		});
	}
	//获取单位
	const getunitList = async () => {
		const data = await getShipments('unit', 'tag');
		console.log('getunitList --->', data);
		unitTags.value = [];
		data.forEach((item : any, key : number) => {
			unitTags.value.push(item);
			if (formData.value.unitId === item.value) {
				unitIndex.value = key;
			}
		});
	}
	//获取仓库
	const getwarehouseList = async () => {
		const result = await request({
			url: '/demand/warehouseAll',
		});
		console.log('getwarehouseList --->', result);
		warehouseOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			warehouseOption.value.push({
				label: `${item.warehouseName}`,
				value: item.warehouseId,
				icon: Briefcase,
				color: '#f55442'
			});
			if (formData.value.warehouseId === item.warehouseId) {
				formData.value.warehouse = [item.warehouseId];
				warehouseIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.warehouse;
				let type = '';
				if (!route.query.id) {
					type = '/addProduct';
				} else {
					type = '/updateProduct';
				}
				//
				const result = await request({
					url: '/demand' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});

				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//图片上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.imageUrl = res.t;
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	.el-upload-list--text {
		display: none;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>